package com.ray.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DuplicateOrderUpdateRecordBean;
import com.ray.bean.FeedOrderDetailBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.exception.ServiceException;
import com.ray.pojo.MyUser;
import com.ray.service.DuplicateOrderUpdateRecordsService;
import com.ray.service.WarehouseService;
import com.ray.util.ExcelExportUtil;
import com.ray.util.RequestUtil;
import com.ray.util.ResponseUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;

import net.sf.json.JSONArray;

/**
 * 仓库控制层
* <p>Title: WarehouseController</p>  
* <p>Description: </p>  
* @author 李斌  
* @date 2018年9月14日
 */
@Controller
@RequestMapping("/warehouse")
public class WarehouseController {
	
	@Autowired
	WarehouseService warehouseService;
	@Autowired
	DuplicateOrderUpdateRecordsService duplicateOrderUpdateRecordsService;
	
	/**
	 * @throws CloneNotSupportedException 
	 * 采购入库
	* @date 2018年9月14日 上午11:22:04 
	* @author 李斌
	* @return Map<String,Object> 
	* @throws
	 */
	@RequestMapping("/saveWarehouseInByPurchaseOrder")
	@ResponseBody
	public Map<String,String> saveWarehouseInByPurchaseOrder(HttpServletRequest request) throws CloneNotSupportedException{
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		String message = warehouseService.saveWarehouseInByPurchaseOrder(map,request);
		return ResponseUtil.ResponseResult("保存成功 "+message);
	};
	
	/**
	 * @throws CloneNotSupportedException 
	 * 无采购单入库
	 * @date 2018年9月15日 下午3:09:33 
	 * @author 李斌
	 * @return Map<String,Object> 
	 * @throws
	 */
	@RequestMapping("/saveWarehouseInNotPurchaseOrder")
	@ResponseBody
	public Map<String,String> saveWarehouseInNotPurchaseOrder(HttpServletRequest request) throws CloneNotSupportedException{
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		String message = warehouseService.saveWarehouseNotPurchaseOrder(map,request);
		return ResponseUtil.ResponseResult("保存成功 "+message);
	}
	
	/**
	 * @throws CloneNotSupportedException 
	 * 投料单+物料领料出库+发料到外协
	 * @date 2018年9月15日 下午3:46:53 
	 * @author 李斌
	 * @return Map<String,String> 
	 * @throws
	 */ 
	@RequestMapping("/saveWarehouseOut")
	@ResponseBody
	public Map<String,String> saveWarehouseOut(HttpServletRequest request) throws CloneNotSupportedException{
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		String message = warehouseService.saveWarehouseOut(map,request);
		return ResponseUtil.ResponseResult("保存成功 "+message);
	}

	/**
	 * @throws CloneNotSupportedException 
	 * 出入库审核
	* @date 2018年9月15日 下午4:13:08 
	* @author 李斌
	* @return Map<String,String> 
	* @throws
	 */
	@RequestMapping("/approvalWarehouse")
	@ResponseBody
	public Map<String,String> approvalWarehouse(HttpServletRequest request,int status) throws CloneNotSupportedException{
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		String message = warehouseService.approvalWarehouse(map,status,request);
		return ResponseUtil.ResponseResult(message);
	}
	
	@RequestMapping("/approvalAllWarehouse")
	@ResponseBody
	public Map<String,String> approvalAllWarehouse(HttpServletRequest request,int status) throws CloneNotSupportedException{
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		String message = warehouseService.approvalAllWarehouse(map,status,request);
		return ResponseUtil.ResponseResult(message);
	}
	
	/**
	 * 删除出入库记录
	* @date 2018年9月18日 下午4:59:05 
	* @author 李斌
	* @return Map<String,String> 
	* @throws
	 */
	@RequestMapping("/deleteWarehouse") 
	public Map<String,String> deleteWarehouse(HttpServletRequest request){
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		warehouseService.deleteWarehouse(map);
		return ResponseUtil.ResponseResult("操作成功");
	}
	
	/**
	 * 修改出入库
	* @date 2018年9月19日 上午8:36:59 
	* @author 李斌
	* @return Map<String,String> 
	* @throws
	 */
	@RequestMapping("/updateWarehouse")
	@ResponseBody
	public Map<String,String> updateWarehouse(HttpServletRequest request){
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		warehouseService.updateWarehouse(map);
		return ResponseUtil.ResponseResult("操作成功");
	}
	
	/**
	 * 获取出入库记录
	* @date 2018年9月19日 下午1:36:45 
	* @author 李斌
	* @return DatatablesViewPageBean<WarehouseInOutDetailBean> 
	* @throws
	 */
	@RequestMapping("/getWarehouseInOutDetaliList")
	@ResponseBody
	public DatatablesViewPageBean<WarehouseInOutDetailBean> getWarehouseInOutDetaliList(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return warehouseService.getWarehouseInOutDetaliList(map);
	}
	
	
	/**
	 * 财务出入库记录
	 * @param request
	 * @return
	 */
	@RequestMapping("/getWarehouseInOutDetaliListFromFinance")
	@ResponseBody
	public Map getWarehouseInOutDetaliListFromFinance(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		Map retuenMap=warehouseService.getInOutSumPrice(map);
		retuenMap.put("listData", warehouseService.getWarehouseInOutDetaliList(map));
		return ResponseUtil.ResponseResult(retuenMap);
	}
	
	
	
	
	/**
	 * 获取出入库发送消息的记录
	* @date 2018年9月19日 下午2:17:03 
	* @author 李斌
	* @return DatatablesViewPageBean<WarehouseInOutDetailBean> 
	* @throws
	 */
	@RequestMapping("/getWarehouseInOutDetailByIds")
	@ResponseBody 
	public DatatablesViewPageBean<WarehouseInOutDetailBean> getWarehouseInOutDetailByIds(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return warehouseService.getWarehouseInOutDetailByIds(map);
	}
	
	/**
	 * 获取出入库制单人
	* @date 2018年9月19日 下午4:02:42 
	* @author 李斌
	* @return List<UserBean> 
	* @throws
	 */
	@RequestMapping("/getWarehouseInOutCreateUser")
	@ResponseBody
	public Map<String,Object> getWarehouseInOutCreateUser(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.getWarehouseInOutCreateUser(map));
	}
	
	/**
	 * 获取出入库所有的客户
	* @date 2018年9月19日 下午4:09:38 
	* @author 李斌
	* @return List<String> 
	* @throws
	 */
	@RequestMapping("/getCustomerNameByWarehouse")
	@ResponseBody
	public Map<String,Object> getCustomerNameByWarehouse(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.getCustomerNameByWarehouse(map));
	}
	
	/**
	 * @throws IOException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 * 导出出入库记录
	* @date 2018年7月27日 上午7:52:41 
	* @author 李斌
	* @return Map<String,Object> 
	* @throws
	 */
	@ResponseBody
	@RequestMapping(value="/exportExcelFileByWarehouse",method=RequestMethod.GET)
	public void exportExcelFileByWarehouse(HttpServletRequest request,HttpServletResponse response) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		 Map<String, Object> map = RequestUtil.getRequestAllParam(request);
		 DatatablesViewPageBean<WarehouseInOutDetailBean> warehouseInOutDetailList = warehouseService.getWarehouseInOutDetaliList(map);
		 if(warehouseInOutDetailList==null || warehouseInOutDetailList.getReturnData()==null || warehouseInOutDetailList.getReturnData().size()<1) {
			 throw new ServiceException("需要导出的出入库记录为空");
		 }
		 for(WarehouseInOutDetailBean warehouseInOutDetailBean:warehouseInOutDetailList.getReturnData()) {
			 if(warehouseInOutDetailBean.getType()==2||warehouseInOutDetailBean.getType()==5 || warehouseInOutDetailBean.getType()==9 ) {
				 warehouseInOutDetailBean.setExportType("出库");
			 }else {
				 warehouseInOutDetailBean.setExportType("入库");
			 }
			 if(warehouseInOutDetailBean.getStatus()==1) {
				 warehouseInOutDetailBean.setExportStatus("已审核");
			 }else if(warehouseInOutDetailBean.getStatus()==2) {
				 warehouseInOutDetailBean.setExportStatus("已退回");
			 }else {
				 warehouseInOutDetailBean.setExportStatus("未审核");
			 }
			 warehouseInOutDetailBean.setIsTaxStr();
		 }
		 String [] fields  = {"exportType","inDay","companyOrderId","factoryNo","customerNo","customerName","providerName","materialName","color","colorDescription","model","materialDeptName","providerNo","position","inCountPrice","inOutUnit","count","scrapCount","inOutMoney","selfOutFuCount","exportStatus","createUser","createTime","approvalUser","approvalTime","remark","isTaxStr"};
		 String [] heads = {"类型","入库日期","订单编号","工厂型号","客户型号","客户名称","供应商","物料名称","色号","描述","规格","物料部门","供方编号","仓位","出入库单价","单位","数量","报废数量","金额","交接数","状态","制单人","制单时间","审核人","审核时间","备注","是否含税"};
		 String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		 File excelFile=ExcelExportUtil.createExcelFile(warehouseInOutDetailList.getReturnData(),tempFolder,heads,fields);
		 ResponseUtil.downloadfile(response, excelFile, "出入库记录.xlsx", true);
	}
	
	/**
	 * 获取出入库汇总
	* @date 2018年9月20日 上午8:37:43 
	* @author 李斌
	* @return DatatablesViewPageBean<WarehouseInOutDetailBean> 
	* @throws
	 */
	@RequestMapping("/getInOutSummary")
	@ResponseBody
	public DatatablesViewPageBean<WarehouseInOutDetailBean> getInOutSummary(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return warehouseService.getInOutSummary(map);
	}
	
	/**
	 * 根据库存信息获取出入库
	* @date 2018年9月20日 上午11:00:55 
	* @author 李斌
	* @return List<WarehouseInOutDetailBean> 
	* @throws
	 */
	@ResponseBody
	@RequestMapping("/getWarehouseInOutDetaliListByMaterial")
	public Map<String,Object> getWarehouseInOutDetaliListByMaterial(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.getWarehouseInOutDetaliListByMaterial(map));
	}
	
	/**
	 * 获取投料单领料+物料领料数据
	* @date 2018年9月20日 下午1:47:13 
	* @author 李斌
	* @return DatatablesViewPageBean<FeedOrderDetailBean> 
	* @throws
	 */
	@RequestMapping("/getFeedMaterialData")
	@ResponseBody
	public Map<String,Object> getFeedMaterialData(HttpServletRequest request){
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.getFeedMaterialData(map));
	}
	
	/**
	 * 获取某订单成品出库数量
	 * @param request
	 * @return
	 */
	@RequestMapping("/getFinishOutOrder")
	@ResponseBody
	public Map<String,Object> getFinishOutOrder(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.getFinishOutOrder(map));
	}
	
	@RequestMapping("/saveOutToOrder")
	@ResponseBody
	public Map<String,Object> saveOutToOrder(HttpServletRequest request) throws CloneNotSupportedException{
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		checkMaterialToOrder(map);
		warehouseService.saveOutToOrder(map,request);
		return ResponseUtil.ResponseResult("出库成功");
	}
	
	
	//校验是否可修改
	public void checkMaterialToOrder(Map<String,Object> map){
		CompanyMaterialTableBean companyMaterialTable = JSONObject.parseObject(map.get("materialData").toString(),CompanyMaterialTableBean.class);
		OrderInfoDetailBean orderInfoDetail = JSONObject.parseObject(map.get("orderData").toString(),OrderInfoDetailBean.class);
		OrderInfoDetailBean copeOrder = new OrderInfoDetailBean();
		int i = 0;
		BeanUtils.copyProperties(orderInfoDetail, copeOrder);
		if(orderInfoDetail.getIsReadColor()!=2) {
			orderInfoDetail.setColor(companyMaterialTable.getColor());
			orderInfoDetail.setColorDescription(companyMaterialTable.getColorDescription());
		}
		orderInfoDetail.setMaterialModel(companyMaterialTable.getModel());
		
		boolean isExists = duplicateOrderUpdateRecordsService.checkExists(orderInfoDetail,map.get("loginCompany").toString());
		if(isExists) {
			duplicateOrderUpdateRecordsService.chechIsApproval(orderInfoDetail,map.get("loginCompany").toString());
		}else {
			//如果不相等
			boolean isEqu = duplicateOrderUpdateRecordsService.orderAndMaterialIsEqually(copeOrder, orderInfoDetail);
			if(!isEqu) {
				DuplicateOrderUpdateRecordBean duplicateOrderUpdateRecordBean = new DuplicateOrderUpdateRecordBean(copeOrder,orderInfoDetail);
				duplicateOrderUpdateRecordBean.setMaterialCode(companyMaterialTable.getMaterialCode());
				duplicateOrderUpdateRecordBean.setUpdateUserId(map.get("loginUserId").toString());
				duplicateOrderUpdateRecordBean.setUpdateUserName(map.get("loginUserName").toString());
				duplicateOrderUpdateRecordBean.setCompany(map.get("loginCompany").toString());
				boolean haveSendMessage = true;
				duplicateOrderUpdateRecordsService.addDuplicateOrderUpdateRecords(duplicateOrderUpdateRecordBean,map,haveSendMessage);
				i++;
			}
		}
		Assert.isTrue(i==0, "订单物料信息被修改,请先去审核");
	}
	
	/**
	 * 半成品出库
	 * @param request
	 * @return
	 */
	@RequestMapping("/getBlankMaterialData")
	@ResponseBody
	public DatatablesViewPageBean<WarehouseInOutDetailBean> getBlankMaterialData(HttpServletRequest request){
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		return warehouseService.getBlankMaterialData(map);
	}
	
	/**
	 * 保存半成品出库单
	 * @return
	 * @throws CloneNotSupportedException 
	 */
	@RequestMapping("/saveBlankMaterialToCustomer")
	@ResponseBody
	public Map<String,Object> saveBlankMaterialToCustomer(WarehouseInOutDetailBean wiodb,HttpServletRequest request) throws CloneNotSupportedException{
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		String message = warehouseService.saveBlankMaterialToCustomer(wiodb,map,request);
		return ResponseUtil.ResponseResult("操作成功 "+(message==null?"":message));
	}
	
	
	/**
	 * 库存盘点
	 * type 类型  11盘点入库   12 盘点出库
	 * orderId (订单编号)
	 * rowIndex 行号
	 * materialCode (原料盘点时用 物料代码)
	 * count 数量
	 * warehouseType 仓库类型
	 * noCount 不合格数
	 * jsonArray (批量字符串)
	 * @param request
	 * @return
	 * @throws CloneNotSupportedException 
	 */
	@RequestMapping("/materialStockTaking")
	@ResponseBody
	public Map materialStockTaking(HttpServletRequest request) throws CloneNotSupportedException {
		Map map=RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.materialStockTaking(map,request,5));
	}
	
	
	/**
	 * 车间需要退回的物料数量
	 * @return
	 * @throws  
	 */
	@RequestMapping("/workShopNeedReturnMaterial")
	@ResponseBody
	public Map<String,Object> workShopNeedReturnMaterial(HttpServletRequest request) {
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.workShopNeedReturnMaterial(map));
	}
	
	
	/**
	 * 车间多余物料退回至仓库
	 * orderId 订单编号
	 * rowIndex 行号
	 * machining 物料类型
	 * materialCode 物料代码
	 * workShopName 车间id
	 * materialCount 物料单位退回数量
	 * @return
	 */
	@RequestMapping("/workShopSurplusMaterialReturnToWarehouse")
	@ResponseBody
	public Map<String,Object> workShopSurplusMaterialReturnToWarehouse(HttpServletRequest request) {
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.workShopSurplusMaterialReturnToWarehouse(map,request));
	}
	
	
	/**
	 * 车间多余物料退回至仓库
	 * orderId 订单编号
	 * rowIndex 行号
	 * machining 物料类型
	 * materialCode 物料代码
	 * workShopName 车间id
	 * materialCount 物料单位退回数量
	 * @return
	 */
	@RequestMapping("/workShopSurplusMaterialReturnToWarehouseAll")
	@ResponseBody
	public Map<String,Object> workShopSurplusMaterialReturnToWarehouseAll(HttpServletRequest request) {
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.workShopSurplusMaterialReturnToWarehouseAll(map,request));
	}
	
	
	
	/**
	 * 物料转仓
	 * jsonArray 
	 * materialCode 物料代码 
	 * materialName 物料名称 
	 * model 规格
	 * color 色号
	 * providerName 供应商
	 * inOutUnit 出入库单位
	 * count 数量
	 * type 12(等同于盘点出库)
	 * warehouseType 原仓位
	 * ralationWarehouse 转入仓位
	 * isAduit 是否库存盘点
	 * @return
	 * @throws CloneNotSupportedException 
	 */
	@RequestMapping("/warehouseToOtherWarehouse")
	@ResponseBody
	public Map<String,Object> warehouseToOtherWarehouse(HttpServletRequest request) throws CloneNotSupportedException {
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.materialStockTaking(map,request,6));
	}
	
	
	/**
	 * @throws CloneNotSupportedException 
	 * 投料单+物料领料出库+发料到外协
	 * @date 2018年9月15日 下午3:46:53 
	 * @author 李斌
	 * @return Map<String,String> 
	 * @throws
	 */ 
	@RequestMapping("/savePutOutFromWarehouse")
	@ResponseBody
	public Map<String,String> savePutOutFromWarehouse(HttpServletRequest request,HttpServletResponse response) throws CloneNotSupportedException{
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		String message = warehouseService.savePutOutFromWarehouse(map,request,response);
		return ResponseUtil.ResponseResult("保存成功 "+message);
	}
	
	
	
	/**
	 * @throws Exception 
	 * @throws CloneNotSupportedException 
	 * 成品转物料功能
	 * @date 2018年9月15日 下午3:46:53 
	 * @author 李斌
	 * @return Map<String,String> 
	 * @throws
	 */ 
	@RequestMapping("/finishedProductToMaterial")
	@ResponseBody
	public Map<String,String> finishedProductToMaterial(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		String message = warehouseService.finishedProductToMaterial(map,request);
		return ResponseUtil.ResponseResult("保存成功 "+message);
	}
	
	/**
	 * 销毁出入库记录
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toVoidInOutRecord")
	@ResponseBody
	public Map<String,String> toVoidInOutRecord(HttpServletRequest request,HttpServletResponse response) throws Exception{
		MyUser myUser=RequestUtil.getLoginUser(request);
		Boolean bool=warehouseService.checkToVoidInOutRecordPermission(myUser);
		Assert.isTrue(bool,"没有权限");
		Map<String,String> map = RequestUtil.getRequestAllParam(request);
		StringUtil.checkIsTrue(map, "idArray", "请选择需退回的记录");
		String idArray =map.get("idArray");
		JSONArray jsonArray=JSONArray.fromObject(idArray);
		List<String> idList=jsonArray.subList(0, jsonArray.size());
		for(String id:idList) {
			map.put("id", id);
			warehouseService.toVoidInOutRecord(map);
		}
		return ResponseUtil.ResponseResult(ReturnStringUtil.OPERATION_SUCCESS);
	}
	
	
	/**
	 * 无订单从车间退回至仓库
	 * materialCode 物料代码
	 * workShopId 车间id
	 * count 退回数量
	 * warehouseType:4 仓库类型固定为4
	 * materialName 物料名称
	 * color 色号
	 * providerName 供应商名称
	 * model 规格型号
	 * inOutUnit 入库单位
	 * remark 备注
	 * array 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/noOrderReturnToWarehouse")
	@ResponseBody
	public Map<String,String> noOrderReturnToWarehouse(HttpServletRequest request,HttpServletResponse response) throws Exception{
		MyUser myUser=RequestUtil.getLoginUser(request);
		Map map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseService.noOrderReturnToWarehouse(map,request));
	}
	
	
	
	
	
	
	
}
 